package demo.Socket.Grass_num_game;

import com.sun.corba.se.impl.encoding.CDROutputObject;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/21-08-21-16:10
 * @Description：demo.Socket.Grass_num_game
 */
public class Grass_Server {
    public static void main(String[] args) {
        ServerSocket socket= null;
        Socket accept = null;
        try {
            socket= new ServerSocket(Integer.parseInt(PropertiesUtils.properties.getProperty("port")));
            while (true){
                accept = socket.accept();
                Socket finalAccept = accept;
                new Thread(new Runnable() {
                    int number = new Random().nextInt(101);
                    int grass_count = 0;
                    @Override
                    public void run() {
                        int grass_num;
                        try {
                            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(finalAccept.getOutputStream()));
                            writer.write("欢迎体验猜数字游戏，游戏开始啦！（0-100)\r\n");
                            writer.flush();
                            BufferedReader reader = null;
                            reader = new BufferedReader(new InputStreamReader(finalAccept.getInputStream()));
                            while(true){

                                grass_num = Integer.parseInt(reader.readLine());
                                System.out.println(grass_num);
                                grass_count++;
                                if(grass_num == number){
                                    writer.write("恭喜您，只用了" + grass_count + "次机会就猜出" + number);
                                    writer.newLine();
                                    writer.flush();
                                    break;
                                }else if(grass_num > number){
                                    writer.write("您可以往小了猜猜看呢\r\n");
                                    writer.flush();
                                }else if(grass_num < number){
                                    writer.write("要不往大的猜猜看？\r\n");
                                    writer.flush();
                                }

                                if(grass_count == 3){
                                    writer.write("很遗憾你的机会用完啦！\r\n");
                                    writer.flush();
                                }
                            }
                            writer.close();
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
